<?php
/**
 * Created by bianquan
 * CommonUser: ZhuYunlong
 * Email: 920200256@qq.com
 * Date: 2019/1/12
 * Time: 20:07
 */

namespace app\admin\logic\auth;

use app\lib\exception\TokenException;
use app\lib\Instance;
use Firebase\JWT\JWT;
use RuntimeException;

class Token
{
    use Instance;

    protected $token;

    protected $adminID;

    protected $roleID;

    /**
     * @var \app\admin\model\auth\Admin
     */
    protected $admin;

    /**
     * @var \app\admin\model\auth\Role
     */
    protected $role;

    protected static $config;

    public function __construct()
    {
        if ($this->token === null) {
            $this->token = request()->header('X-Api-Token');
        }
    }


    /**
     * 生成令牌
     * @return null|string
     */
    public static function generateToken(\app\admin\model\auth\Admin $admin)
    {
        $nowTime = time();
        $tokenMsg = [
            'iss' => env('jwt.iss'), //签发者
            'aud' => env('jwt.aud'), //jwt所面向的用户
            'iat' => env('jwt.iat'), //签发时间
            'nbf' => env('jwt.nbf'), //在什么时间之后该jwt才可用
            'exp' => $nowTime + env('jwt.exp'), //过期时间
            'data' => [
                'id' => $admin->admin_id,
                'role_id' => $admin->role_id,
            ]
        ];
        return JWT::encode($tokenMsg, env('jwt.key'));
    }


    /**
     * 验证token是否合法或者是否过期
     * @return Token
     * @throws TokenException
     */
    public function checkToken()
    {
        if(empty($this->token)) {
            throw new TokenException('Token不存在，请登录');
        }
        try {
            JWT::$leeway = env('jwt.leeway');
            $decoded = JWT::decode($this->token,  env('jwt.key'), array('HS256'));
            $arr = (array)$decoded;
            if ($arr['exp'] < time()) {
                throw new TokenException('登录已失效，请重新登录');
            } else {
                $this->adminID = $arr['data']->id;
                $this->roleID = $arr['data']->role_id;
            }
        } catch(RuntimeException $e) {
            throw new TokenException($e->getMessage());
        }
        return $this;
    }

    public function getAdminID() {
        return $this->adminID;
    }

    public function getRoleID() {
        return $this->roleID;
    }

    /**
     * 获取登录的管理员
     * @return \app\admin\model\auth\Admin|array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function admin() {
        if ($this->admin === null) {
            $this->admin = \app\admin\model\auth\Admin::find($this->adminID);
        }
        return $this->admin;
    }

    public function role() {
        if ($this->role === null) {
            $this->role = \app\admin\model\auth\Role::find($this->roleID);
        }
        return $this->role;
    }
}